package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.glory.cqaospda.R
import com.glory.cqaospda.adapter.InspectAdapter
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.SpotCheckInfoBean
import com.glory.cqaospda.viewmodel.InspectModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.google.gson.JsonObject
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import kotlinx.android.synthetic.main.activity_inspect.*
import kotlinx.android.synthetic.main.activity_title.*
import kotlinx.android.synthetic.main.inspect_layout.*
import java.lang.Exception

class InspectActivity : BaseActivity<InspectModel>() {

    private var codePop: PopWindowsUtils.GeneralPop? = null
    var list: ArrayList<String> = ArrayList()
    var lotid = ""
    var maintenanceItem = ""
    var inspectItemList:SpotCheckInfoBean.ProCheckList? = null
    var insopectAdapter: InspectAdapter? = null
    var proCheckList:SpotCheckInfoBean.ProCheckList? = null
    var spotcheckinfoList = ArrayList<SpotCheckInfoBean.ProCheckList>()
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@InspectActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }


    override fun initData() {

        viewModel.defUI.callObserve.observe(this@InspectActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("成功送检", true)
                        intent.setClass(this, HomeActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                    2 -> {
                        val spotcheckinfobean = it.item as SpotCheckInfoBean
                        insopectAdapter!!.setEqpID(spotcheckinfobean.equipmentname)
                        insopectAdapter!!.setList(spotcheckinfobean.prochecklist)
                        insopectAdapter!!.notifyDataSetChanged()
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }

        flPositionList.setOnClickListener {
            if (codePop == null) {
                codePop = PopWindowsUtils.getOneChoosePop(this, flType.width, list,
                    ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(string: String, potion: Int) {
                            tvType.text = string
                            val map = JsonObject()
                            map.addProperty("EquipmentName", etEqpId.text.toString())
                            map.addProperty("CheckType", string)
                            insopectAdapter!!.setList(null)
                            insopectAdapter!!.notifyDataSetChanged()
                            viewModel.defaultSpotCheckInfo(map)
                        }
                    }
                )
            }

            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivTypeArrow)
                codePop?.showAsDropDown(flType, 0, 0)
            }
        }

        insopectAdapter!!.setOnItemClickListener { itemList, position ->
            if (Constant.isFastClick()) {
                proCheckList = itemList
                spotcheckinfoList.add(itemList)
                if (tvType.text.toString() == "buy off"){
                    intent.putExtra("type", "inspect")
                }else{
                    intent.putExtra("type", "inspect0")
                }

                val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                intent.setClass(this, clazz)
                startActivityForResult(intent, 1)
            }
        }
        insopectAdapter!!.setOnItemLongClickListener{ itemList, position ->
            if (Constant.IsInspectItemLongClickListener) {
                inspectItemList = itemList
                intent.putExtra("type", "inspectItem")
                val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                intent.setClass(this, clazz)
                startActivityForResult(intent, 1)
            }
        }

        rvInspectList.setOnFocusChangeListener { view: View, b: Boolean ->
            if (b) {
                etEqpId.requestFocus()
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        tvTitle.text = "送检"
        tvBaseSubmit.text = "送检"
        tvBaseSubmit.visibility = View.GONE
        list.add("buy off")
        list.add("全检")
        list.add("QA")
//        list.add("bin check")
        FreeApi_ActivityManager.getActivityManager().addActivity(this)
        initRecyclerView(rvInspectList, this)
        insopectAdapter = InspectAdapter(null)
        rvInspectList.adapter = insopectAdapter
        tvUserName.text = Constant.UserName

        val instance = MyApp.instance
        instance!!.handler = handler
    }

    override fun layoutId(): Int {
        return R.layout.activity_inspect
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                1 -> {
                    val extras = data!!.extras
                    lotid = extras!!.getString("lotId").toString()
                    maintenanceItem = extras.getString("maintenanceItem").toString()

                    if (proCheckList!!.lotid == lotid){
                        val map = JsonObject()
                        map.addProperty("OrderId", spotcheckinfoList[0].order_id)
                        map.addProperty("EquipmentName", etEqpId.text.toString())
                        map.addProperty("CheckType", spotcheckinfoList[0].checktype)
                        map.addProperty("BuyOff_Type", spotcheckinfoList[0].buyoff_type)
                        map.addProperty("ReelID", maintenanceItem)
                        map.addProperty("LotNo", lotid)
                        viewModel.defaultSendCheck(map)
                    }else{
                        intent.putExtra("type", "inspectLot")
                        intent.setClass(this, SkipDialogActivity::class.java)
                        startActivityForResult(intent, 1)
                    }

                }
                2 ->{
                    val map = JsonObject()
                    map.addProperty("OrderId", spotcheckinfoList[0].order_id)
                    map.addProperty("EquipmentName", etEqpId.text.toString())
                    map.addProperty("CheckType", spotcheckinfoList[0].checktype)
                    map.addProperty("BuyOff_Type", spotcheckinfoList[0].buyoff_type)
                    map.addProperty("ReelID", maintenanceItem)
                    map.addProperty("LotNo", lotid)
                    viewModel.defaultSendCheck(map)
                }
                3 -> {
                    val extras = data!!.extras
                    val reason = extras!!.getString("reason").toString()
                    if (inspectItemList == null){
                        viewModel.defUI.toastEvent.value = ToastMessageBean("系统出错",false)
                        return
                    }
                    val map = JsonObject()
                    map.addProperty("OrderID", inspectItemList!!.order_id)
                    map.addProperty("ReasonText", reason)
                    map.addProperty("CheckType", tvType.text.toString())
                    viewModel.defaultCancelBuyoff(map)
                }
                108 -> {
                    finish()
                }
            }
        }
    }

    protected fun initRecyclerView(recyclerView: RecyclerView, context: Context?) {
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.addItemDecoration(DividerItemDecoration(context, 1))
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 520) {
            try {
                val view = window.decorView.findFocus() as EditText
                when (view) {
                    etEqpId -> {
                        etEqpId.setText("")
                    }
                }
            } catch (e: Exception){
                println(e.message)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }
}